<?php

namespace App\Http\Controllers\AppApi\News;

use App\Http\Controllers\AppApi\BaseController;
use App\Repositories\NewsRepository;
use Illuminate\Http\Request;

class IndexController extends BaseController
{
    private $newsRepository;

    public function __construct(NewsRepository $newsRepository,Request $request)
    {
        parent::__construct();
        $this->newsRepository = $newsRepository;

        if ($request->app_access!=$this->app_access) {
            return $this->returnJson(-1,'接口权限错误');
        }
//        if (!$request->token) {
//            return $this->returnJson(-2,'参数错误');
//        }
    }

    /**
     * 获取最新的咨询
     * /api/news/index
    */
    public function index()
    {
      //  exit('aaaaaaaaaaf');
        $list = $this->newsRepository->getNews();
        return $this->output($list);
    }

    /**
     * /api/news/detail
    */
    public function detail(Request $request)
    {

        //exit('sssssssss');
        $new_id = intval($request->input('id',0));
        if(!$new_id){
            return $this->output([],'缺失参数',-2);
        }
        $content = $this->newsRepository->getNewsDetail($new_id);
        return $this->output($content);
    }

    /**
     * 发布资讯
     */
    public function add(Request $request)
    {
        $token = $request->token;
        $type = $request->type;

        if (!$token || !in_array($type,[1,2,3,4])) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }

        //获取参数
        $content = $request->post('content');
        $thumb = $request->post('thumb');
        $title = $request->post('title');

        //校验参数
        if (!($content && $thumb && $title)) {
            return $this->toJson(-2);
        }
        //这里获取记录的类型
        $insertData = [
            'cid' => $uid,
            'title'=>$title,
            'thumb'=>$thumb,
            'content'=>$content,
            'created_at'=>time(),
            'updated_at'=>time()
        ];

        $resNews = $this->newsRepository->addNew($insertData);
        if (!$resNews) { return $this->toJson(-24); }
        return $this->toJson(0);
    }

    /**
     * 制作者：九哥
     * 点赞
     */
    public function setPraise(Request $request)
    {
        if ($request->app_access!=$this->app_access) {
            return $this->toJson(-1);
        }
        $token = $request->token;
        $type = $request->type;
        $cate = $request->cate;
        $newsId = $request->newsId;
        if (!$token || !in_array($type,[1,2,3,4])) {
            return $this->toJson(-2);
        }
        $uid = $this->accessGet($token);
        if (!$uid) { return $this->toJson(-13); }
        $resNews = $this->newsRepository->setPraise($newsId,$uid);
        if (!$resNews['status']) {  return $this->output([],$resNews['msg'],500); }
        return $this->toJson(0,array('praise'=>$resNews['data']));
    }
}